# mastermind.rb
# den 14 mars 2007
# Janne Berg

class Mastermind

  @@colours = {'y'=>'yellow','g'=>'green', 'b'=>'blue', 'r'=>'red', 'w'=>'white', 'o'=>'orange'}

  def initialize
    puts "creating master"
    @master = Array.new
    4.times do
      @master << @@colours.keys.fetch(rand(@@colours.keys.length))
    end
  #  p @master
  end

  def play
    8.times do |try|
      found = {:colour=>0,:colour_and_pos=>0}
      puts "Round #{try+1}, make your guess" 
      incoming = $stdin.gets.chomp
      draw = incoming.split(//)
      
      @master.each_index do |i|
        if draw[i] == @master[i]
          found[:colour_and_pos] = found[:colour_and_pos] + 1
          draw[i] = nil
        elsif draw.include?(@master[i])
          found[:colour] = found[:colour] + 1
          draw[draw.index(@master[i])] = nil
        end
      end
      
      puts "You guessed #{@@colours[incoming[0,1]]} #{@@colours[incoming[1,1]]} #{@@colours[incoming[2,1]]} #{@@colours[incoming[3,1]]}"
      if found[:colour_and_pos] == 4
        puts "Congratulations you solved it in just #{try} tries"
        return
      end
      if found[:colour_and_pos] == 0 && found[:colour] == 0
        puts "No hits, try again "
      else
        print "#{found[:colour_and_pos]} where correct " if found[:colour_and_pos] > 0
        print "#{found[:colour]} where the right colour" if found[:colour] > 0
        2.times{puts}
      end
    end
    puts "You failed!"

  end
end
ma = Mastermind.new
ma.play
